/*
 * Copyright 2019-2025 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * https://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.iiifi.kite.boot.web.reactive.version;

import java.lang.reflect.Method;

import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.reactive.result.method.RequestMappingInfo;
import org.springframework.web.reactive.result.method.annotation.RequestMappingHandlerMapping;

import com.iiifi.kite.boot.annotation.ApiVersion;
import com.iiifi.kite.core.util.StringUtils;
import com.iiifi.kite.configuration.KiteProperties;

/**
 * url版本号处理
 *
 * @author kite@iiifi.com 花朝
 */
public class KiteRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    private final KiteProperties properties;

    public KiteRequestMappingHandlerMapping(KiteProperties properties) {
        this.properties = properties;
    }

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        // 默认的规则
        RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType);
        if (mappingInfo == null) {
            return null;
        }

        // 版本号处理
        ApiVersion apiVersion = getApiVersionMappingInfo(method, handlerType);
        if (apiVersion == null) {
            return mappingInfo;
        }
        // 版本
        String version = apiVersion.value();
        if (StringUtils.isBlank(version)) {
            return mappingInfo;
        }

        RequestMappingInfo apiVersionMappingInfo = RequestMappingInfo
                .paths(version)
                .build();

        // 添加版本号
        mappingInfo = apiVersionMappingInfo.combine(mappingInfo);

        // 统一添加应用名，consumes
        if (apiVersion.useAppName()) {
            String applicationName = properties.getName();
            return RequestMappingInfo
                    .paths(applicationName)
                    .build()
                    .combine(mappingInfo);
        }

        return mappingInfo;
    }

    private ApiVersion getApiVersionMappingInfo(Method method, Class<?> handlerType) {
        // 优先获取方法上的版本
        ApiVersion apiVersion = AnnotatedElementUtils.findMergedAnnotation(method, ApiVersion.class);
        // 再次尝试类上的版本
        if (apiVersion == null || StringUtils.isBlank(apiVersion.value())) {
            apiVersion = AnnotatedElementUtils.findMergedAnnotation(handlerType, ApiVersion.class);
        }
        return apiVersion;
    }
}
